#include "createroomreq.h"
#include "ace/String_Base.h"

bool CreateRoomReq::encode(ACE_OutputCDR &cdr)
{
    cdr << ACE_CDR::UShort(_name.length());
    cdr.write_char_array(_name.data(),_name.length());

    cdr << ACE_CDR::UShort(_password.length());
    if(_password.length()){
	cdr.write_char_array(_password.data(),_password.length());
    }

    return cdr.good_bit();
}

ProtoSrv* CreateRoomReq::decode(ACE_InputCDR &cdr)
{
    CreateRoomReq *request = 0;
    ACE_CDR::UShort name_len;
    cdr >> name_len;

    ACE_TCHAR room_name[name_len + 1];

    if(cdr.read_char_array(room_name,name_len)){
	room_name[name_len] = '\0';

        ACE_CDR::UShort pass_len;
        if(cdr >> pass_len){
            if(pass_len) {
		ACE_TCHAR password[pass_len + 1];
		if(cdr.read_char_array(password,pass_len)){
		    password[pass_len] = '\0';
		    request = new CreateRoomReq(room_name,password);
		}
            }
	    else
		request = new CreateRoomReq(room_name);
        }
    }

    return request;
}

ProtoSrv* CreateRoomReq::execute(ACE_SOCK_Stream &peer)
{
    CreateRoomResp *resp = new CreateRoomResp(RoomManager::getInstance()->createRoom(peer,_name,_password));
    if(resp && resp->success()){
        std::auto_ptr<SimpleProtoSrv> notify(new SimpleProtoSrv(PT_NOTIFY_CREATE_ROOM));
        notify->addString(_name);
        TetrixServer::getInstance()->broadcast(notify);
    }

    return resp;
}
